package com.dh.spring.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ConcurrentUtil {
    //TODO 模拟5000个用户同时访问
    private static int requestCount = 50000;
    private static CountDownLatch countDownLatch = new CountDownLatch(requestCount);

    public static void main(String[] args) {
        ConcurrentUtil concurrentUtil = new ConcurrentUtil();
        concurrentUtil.startup();

        try {
            System.out.println("主线程开始阻塞");
            countDownLatch.await();
            System.out.println("主线程开始执行,当前CountDownLatch最终结果为：" + countDownLatch.getCount());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void startup() {

        for(int i = 0; i < requestCount; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    SocketChannel socketChannel = null;
                    try {

                        System.out.println(Thread.currentThread().getName() + " 开始进行远程连接......");
                        socketChannel = SocketChannel.open();
                        socketChannel.configureBlocking(false);
                        socketChannel.connect(new InetSocketAddress("10.33.37.114", 10089));

                        while (socketChannel.finishConnect()) {
                            System.out.println(Thread.currentThread().getName() + " 连接成功，开始执行耗时任务......");
                            try {
                                socketChannel.write(ByteBuffer.wrap(new String(Thread.currentThread().getName() + "发送给服务器消息").getBytes(Charset.forName("UTF-8"))));
                                TimeUnit.MILLISECONDS.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            break;
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                        try {
                            if(null != socketChannel) {
                                socketChannel.shutdownOutput();
                                socketChannel.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "任务执行完成......");
                    }
                }

            }, "客户端 [" + (i+1) + "]").start();
        }



    }
}
